<?php
/**
 * Created by PhpStorm.
 * User: shiyin
 * Date: 2020/6/16
 * Time: 13:49
 */

namespace Danmu;

require __DIR__ . '/vendor/autoload.php';

use Danmu\Traits\SendTrait;

class Server
{

    use SendTrait;

    // 客户端对象
    public $clients = [];

    // websocket
    public $ws;
    public $server;

    public function __construct()
    {

        \Co\run(function () {


            echo 'websocket server start...' . PHP_EOL;

            $server = new \Co\Http\Server('0.0.0.0', 9502, false);
$this->server=$server;
            // websocket
            $server->handle('/ws', function ($request, $ws) {

                // 心跳检测
//                \Swoole\Coroutine::create(function () use ($request) {
//                    $this->clients[$request->fd]['timer_id'] = \Swoole\Timer::tick(5000, $this->ping($request));
//                });

                $this->ws = $ws;
                $ws->upgrade();
                while (true) {

                    print_r($this->server->connections);
                    print_r($this->clients);
                    $frame = $ws->recv();
                    if ($frame == '') break;

                    if ($frame === false) {
                        // 异常、错误退出
                        echo "error : " . swoole_last_error() . "\n";
                        break;
                    }

                    if ($frame->data == "close") {
                        // 关闭链接
                        $ws->close();
                        return;
                    }

                    // 正常响应
                    $data = json_decode($frame->data, true);
                    switch ($data['type']) {
                        case 'text':
                            $this->sendAll($frame->fd, $data['data']);
                            break;
                        case 'pong':
                            $this->clients[$frame->fd]['ping'] -= 1;
                            break;
                        case 'uploadToken':

                            break;
                    }
//                    $ws->push("Hello {$frame->data}!");
//                    $ws->push("How are you, {$frame->data}?");

                }
            });

            // http
            $server->handle('/', function ($request, $response) {
                $response->end(<<<HTML
    <h1>Swoole WebSocket Server</h1>
    <script>
var wsServer = 'ws://118.24.26.76:9502/ws';
var websocket = new WebSocket(wsServer);
websocket.onopen = function (evt) {
    console.log("Connected to WebSocket server.");
    websocket.send('hello');
};

websocket.onclose = function (evt) {
    console.log("Disconnected");
};

websocket.onmessage = function (evt) {
    console.log('Retrieved data from server: ' + evt.data);
};

websocket.onerror = function (evt, e) {
    console.log('Error occured: ' + evt.data);
};
</script>
HTML
                );
            });

            $server->start();

        });

    }

}

// 运行
new Server();